<?php

namespace App\Http\Controllers\Api\V1\Wxpay;

use Illuminate\Http\Request;
use App\Libs\Contracts\PayMent\Wxpay\JsApiNativePay;
use App\Libs\Contracts\PayMent\Wxpay\WeixinPay;
use App\Models\Business;
use App\Models\User;
use App\Models\MemberOrder;
use App\Models\ResumeOrder;
use App\Models\MemberWelfare;
use App\Models\Profit;
use App\Libs\Contracts\PayMent\Wxpay\WxPayApi;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;

class WxpayController extends Controller
{
    /**
     * 购买会员
     */
    public function MemberWxpay(Request $request)
    {
        //先保存数据库
        $openid = $request->openId;
        $memberwelfareId = $request->vipId;
        $res = MemberWelfare::where('memberwelfareId', $memberwelfareId)->first();
        $price = $res['condition'];
        $out_trade_no = order_number($openid);
        $data = [];
        $data['out_trade_no'] = $out_trade_no;
        $data['openid'] = $openid;
        $data['price'] = $price;
        $data['createTime'] = date('Y-m-d H:i:s', time());
        $data['memberwelfareId'] = $memberwelfareId;
        $status = MemberOrder::create($data);
        if (!$status) {
            return $this->apiResponse('', config('errorCode.ORDER_FAILS'));
        }

        //微信支付返回preId
        $orderDetail['orderNo'] = $out_trade_no;
        $orderDetail['totalFee'] = $price * 100;
        $orderDetail['body'] = "购买会员";
        $orderDetail['openId'] = $openid;
        $orderDetail['notifyUrl'] = env('MEMBER_NOTIFY_URL');
        $result = JsApiNativePay::JsApiNativePay($orderDetail);

        //再次签名，给前端返回
        $timestamp = time();
        $signType = "MD5";
        $package = 'prepay_id=' . $result['prepay_id'];
        $nonceStr = nonceStr();
        $resSignRaw = "appId=" . env("APPID") . "&nonceStr=" . $nonceStr . "&package=" . $package . "&signType=" . $signType . "&timeStamp=" . $timestamp . "&key=" . env("APPKEY");
        $resSign = md5($resSignRaw);
        $responseOrder['appId'] = env("APPID");
        $responseOrder['package'] = $package;
        $responseOrder['paySign'] = $resSign;
        $responseOrder['nonceStr'] = $nonceStr;
        $responseOrder['signType'] = $signType;
        $responseOrder['timeStamp'] = $timestamp;
        return $this->apiResponse($responseOrder);
    }
    /**
     * 回调
     */
    public function MemberCallback()
    {
        $postXml = file_get_contents("php://input"); //接收微信参数
        $result = xmlToArray($postXml);
        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            $out_trade_no = $result['out_trade_no'];
            $data['payTime'] = date('Y-m-d H:i:s', time());
            $data['status'] = '1';
            MemberOrder::where('out_trade_no', $out_trade_no)->update($data);
            $aa = MemberOrder::where('out_trade_no', $out_trade_no)->first();
            $openid = $aa['openid'];
            $res = [];
            $res['memberType'] = $aa['memberwelfareId'];
            $res['memberstart'] = date('Y-m-d H:i:s',time());
            $res['memberEnd'] = date('Y-m-d H:i:s', strtotime("+1 year"));
            Business::where('openid', $openid)->update($res);
        }
        echo "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";

    }

    //购买简历
    public function ResumeWxpay(Request $request)
    {
        //先保存数据库
        $openid = $request->header('openId');
        $userId = $request->userId;
        $businessId = $request->businessId;
        $res = User::where('userId', $userId)->first();
        $price = $res['price'];
        $out_trade_no = order_number($openid);
        $data = [];
        $data['userId'] = $userId;
        $data['businessId'] = $businessId;
        $data['out_trade_no'] = $out_trade_no;
        $data['openid'] = $openid;
        $data['price'] = $price;
        $data['createTime'] = date('Y-m-d H:i:s', time());
        $status = ResumeOrder::create($data);
        if (!$status) {
            return $this->apiResponse('', config('errorCode.ORDER_FAILS'));
        }
        //微信支付返回preId
        $orderDetail['orderNo'] = $out_trade_no;
        $orderDetail['totalFee'] = $price * 100;
        $orderDetail['body'] = "购买会员";
        $orderDetail['openId'] = $openid;
        $orderDetail['notifyUrl'] = env('RESUME_NOTIFY_URL');
        $result = JsApiNativePay::JsApiNativePay($orderDetail);

        //再次签名，给前端返回
        $timestamp = time();
        $signType = "MD5";
        $package = 'prepay_id=' . $result['prepay_id'];
        $nonceStr = nonceStr();
        $resSignRaw = "appId=" . env("APPID") . "&nonceStr=" . $nonceStr . "&package=" . $package . "&signType=" . $signType . "&timeStamp=" . $timestamp . "&key=" . env("APPKEY");
        $resSign = md5($resSignRaw);
        $responseOrder['appId'] = env("APPID");
        $responseOrder['package'] = $package;
        $responseOrder['paySign'] = $resSign;
        $responseOrder['nonceStr'] = $nonceStr;
        $responseOrder['signType'] = $signType;
        $responseOrder['timeStamp'] = $timestamp;
        return $this->apiResponse($responseOrder);
    }

    //回调
    public function ResumeCallback()
    {
        $postXml = file_get_contents("php://input"); //接收微信参数
        $result = xmlToArray($postXml);
        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            $out_trade_no = $result['out_trade_no'];
            $data['payTime'] = date('Y-m-d H:i:s', time());
            $data['status'] = '1';
            //修改订单表状态
            ResumeOrder::where('out_trade_no', $out_trade_no)->update($data);

            //给用户付款
            //查找用户openid以及简历价格
            $order = ResumeOrder::where('out_trade_no', $out_trade_no)->first();
            $userId = $order['userId'];
            $user = User::where('userId',$userId)->first();
            $openid = $user['openId'];

            $url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
            $data['mch_appid'] = env('APPID');
            $data['mchid'] = env('MCHID');
            $data['nonce_str'] = nonceStr(32);
            $data['sign_type'] = "MD5";

            $data['partner_trade_no'] = $out_trade_no;
            $data['openid'] = $openid;
            $data['check_name'] = 'NO_CHECK';
            $data['amount'] = 1;
            $data['desc'] = '技师简历所得';
            $data['spbill_create_ip'] = getIp();
            $model = new WxPayApi();
            $key = "";
            $data['sign'] = $model->MakeSign($data, $key);
            $xml = $model->ToXml($data);
            $response = $model->postXmlCurl($xml, $url);
            $arr = xmlToArray($response);
            if (($arr['return_code'] === "SUCCESS") && ($arr['result_code'] === "SUCCESS")) {
                //进入收益表
                $profit = [];
                $profit['price'] = $order['price'];
                $profit['type'] = '商家查阅简历';
                $profit['userId'] = $userId;
                $profit['payTime'] = date('Y-m-d H:i:s', time());
                Profit::create($profit);


            }
        }
        echo "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";


    }


}